package com.zzx.utils;

import java.lang.reflect.Field;
import java.util.Objects;

public class EntityUtils {

    /**
     * 仅填充目标对象中为 null 的字段，保留已有非空值
     *
     * @param source 源对象（数据库实体）
     * @param target 目标对象（前端传参）
     */
    public static void mergeNonNullProperties(Object source, Object target) {
        Objects.requireNonNull(source, "Source object cannot be null");
        Objects.requireNonNull(target, "Target object cannot be null");

        Class<?> clazz = source.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object sourceValue = field.get(source);
                Object targetValue = field.get(target);

                if (targetValue == null && sourceValue != null) {
                    field.set(target, sourceValue);
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Failed to access field: " + field.getName(), e);
            }
        }
    }
}
